package week02;

import java.util.HashMap;
import java.util.Map;

/**
 * @author hgvgh
 * @version 1.0
 * @description 数组的度：https://leetcode-cn.com/problems/degree-of-an-array/
 * @date 2022/1/10
 */
public class DegreeOfAnArray {

  public static void main(String[] args) {
    int[] nums = new int[]{1,2,2,3,1};
    int shortestSubArray = findShortestSubArray(nums);
    System.out.println(shortestSubArray);
  }


  public static int findShortestSubArray(int[] nums) {
    Map<Integer,Integer> countmap=new HashMap<>();
    Map<Integer,Integer> first=new HashMap<>();
    int minlength=nums.length;
    int curmaxcount=0;
    for(int m=0;m<nums.length;m++)
    {
      if(!first.containsKey(nums[m]))
        first.put(nums[m],m);
      countmap.put(nums[m],countmap.getOrDefault(nums[m],0)+1);
      if(countmap.get(nums[m])>=curmaxcount)
      {
        if(countmap.get(nums[m])==curmaxcount)
          minlength=Math.min(m-first.get(nums[m])+1,minlength);
        else
        {minlength=m-first.get(nums[m])+1;curmaxcount=countmap.get(nums[m]);}
      }
    }
    return minlength;
  }

}
